﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace Abam.Code.OAuth
{
    public class YandexUser
    {
        public string Access_Token;
        public string Token_Type;
        public string Display_name;
    }
    
    public class YandexAuthorize
    {
        public static string ClientId
        {
            get { return "b229cc58b24d4279be6dae7dc45d0cda"; }
        }

        public static string ClientSecret
        {
            get { return "9974e067068442128c30bdac0a4d667f"; }
        }

        public static string AuthorizeAddress
        {
            get { return "https://oauth.yandex.ru/authorize?response_type=code&client_id=" + ClientId; }
        }

        public static string GetTokenAddress
        {
            get { return "https://oauth.yandex.ru/token"; }
        }

        private static string GetInfoAddress
        {
            get { return "https://login.yandex.ru/info?format=json&oauth_token="; }
        }

        public static WebResponse GetToken(string code)
        {
            var request = (HttpWebRequest)WebRequest.Create(GetTokenAddress);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            var query = String.Format("grant_type=authorization_code" +
                                      "&code={0}" +
                                      "&client_id={1}" +
                                      "&client_secret={2}", code, ClientId, ClientSecret);

            var parameters = Encoding.UTF8.GetBytes(query);
            request.ContentLength = parameters.Length;

            var sendStream = request.GetRequestStream();
            sendStream.Write(parameters, 0, parameters.Length);
            sendStream.Close();

            var response = request.GetResponse();

            return response;
        }

        public static YandexUser Deserialize(StreamReader streamReader)
        {
            var js = new JavaScriptSerializer();
            var yandexUser = js.Deserialize<YandexUser>(streamReader.ReadToEnd());

            return yandexUser;
        }

        public static YandexUser Info(string token)
        {
            var request = (HttpWebRequest) WebRequest.Create(GetInfoAddress + token);
            request.Method = "GET";

            var response = request.GetResponse();
            var sr = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
            var yandexUser = Deserialize(sr);
            sr.Close();

            return yandexUser;
        }
    }
}